package com.juvepoland.jpdroid.activities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

import com.juvepoland.jpdroid.R;
import com.juvepoland.jpdroid.activities.BasicActivity.AsyncActionClass;
import com.juvepoland.jpdroid.adapters.LazyCommentAdapter;
import com.juvepoland.jpdroid.application.JPdroidApplication;
import com.juvepoland.jpdroid.common.ImageLoader;
import com.juvepoland.jpdroid.managers.impl.CommentManager;
import com.juvepoland.jpdroid.managers.impl.NewsManagerImpl;
import com.juvepoland.jpdroid.models.Comment;
import com.juvepoland.jpdroid.models.News;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

public class SingleNewsActivity extends BasicActivity {
	
	protected NewsManagerImpl newsManager = new NewsManagerImpl();
	protected News news;
	protected int newsId;
	protected ListView list;
	protected LazyCommentAdapter adapter;
	protected TextView newsIDTextView;
	protected int commentIndex = 0;
	protected CommentManager commentManager = new CommentManager();
	protected int commentsCountPerSinglePage = 20;	//TODO dodac do ustawien shared preferences
	
	protected TextView newsContentTextView;
	protected TextView newsTitleTextView;
	protected TextView newsDateTextView;
	
	protected TextView commentsBarTextView;
	protected TextView sourceTextView;
	
	protected ImageView thumbImage;
	
	protected Button btnLoadMore;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.single_news_activity_main_layout);
		list = (ListView) findViewById(R.id.comment_list);
		newsIDTextView = (TextView) findViewById(R.id.news_id);
		
		btnLoadMore = new Button(this);
		btnLoadMore.setText("więcej >>>");
		btnLoadMore.setTypeface(basicFontTypeFace);
		list.addFooterView(btnLoadMore);
		//btnLoadPrev = new Button(this);
		//btnLoadPrev.setTypeface(basicFontTypeFace);
		//btnLoadPrev.setText("<<< wstecz");
		//list.addHeaderView(btnLoadPrev);
		
		Intent intent = getIntent();
		newsId = intent.getIntExtra("news_id", 0);
		news = newsManager.getNews(newsId);

		if(news!=null){
			newsContentTextView = (TextView) findViewById(R.id.news_content);
			newsContentTextView.setTypeface(basicFontTypeFace);
			newsContentTextView.setMovementMethod(LinkMovementMethod.getInstance());
			
			newsTitleTextView = (TextView) findViewById(R.id.title_single);
			newsTitleTextView.setTypeface(basicFontTypeFace);
			
			newsDateTextView = (TextView) findViewById(R.id.date_single);
			newsDateTextView.setTypeface(basicFontTypeFace);
			
			commentsBarTextView = (TextView) findViewById(R.id.comments_bar);
			commentsBarTextView.setText("Komentarze ["+news.getCommentsCount()+"]:");
			commentsBarTextView.setTypeface(basicFontTypeFace);
			
			sourceTextView = (TextView) findViewById(R.id.source_news);
		    sourceTextView.setTypeface(basicFontTypeFace);
		    
		    thumbImage=(ImageView)findViewById(R.id.single_image); //TODO sprawdzić co to
			
			new AsyncActionClass().execute(null);
			
			addListOnClickListener();
			
			addButtonLoadMoreOnClickListener();
		}
		else{
			Toast.makeText(getApplicationContext(), "Błąd! Nie znaleziono wiadomości. ",
					Toast.LENGTH_LONG).show();
			finish();
		}
		
	}
	
	protected void addButtonLoadMoreOnClickListener() {
		
		btnLoadMore.setOnClickListener(new View.OnClickListener() {
		    @Override
		    public void onClick(View arg0) {
		    	
		    		commentIndex = commentIndex+commentsCountPerSinglePage;
			       // int currentPosition = list.getFirstVisiblePosition();
			        new AsyncActionClass().execute(null);
			       
			       
		    	
	
		    }
		});
		
	}

	protected void addListOnClickListener() {
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent singleCommentIntent = new Intent(getApplicationContext(), SingleCommentActivity.class);
				
				TextView tv =  (TextView) arg1.findViewById(R.id.cid);
				singleCommentIntent.putExtra("comment_id", Integer.parseInt(tv.getText().toString()));
				singleCommentIntent.putExtra("news_id", Integer.parseInt(newsIDTextView.getText().toString()));
				startActivity(singleCommentIntent);
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.single_news_menu, menu);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		JPdroidApplication app = (JPdroidApplication)getApplicationContext();
		MenuItem commentMenuItem = menu.findItem(R.id.comment_bookmark);
		if(app.isUserLogged()){
			if(commentMenuItem!=null){
				commentMenuItem.setVisible(true);
			}
		}
		else{
			if(commentMenuItem!=null){
				commentMenuItem.setVisible(false);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if(item.getItemId() == R.id.share_bookmark){
			Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			String newsUrl = "http://www.juvepoland.com/news.php?id="+news.getId();
			String shareBody = " JuvePoland.com: '"+news.getTitle()+"' - "+newsUrl;
			sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
			sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
			startActivity(Intent.createChooser(sharingIntent, "Udostępnij poprzez:"));
			return true;
		}
		else if(item.getItemId() == R.id.comment_bookmark){
			if(news.getCommentEnabled()==1){
				Intent sendCommentIntent = new Intent(getApplicationContext(), SendCommentActivity.class);
				sendCommentIntent.putExtra("news_id", news.getId());
				startActivity(sendCommentIntent);
			}
			else{
				Toast.makeText(getApplicationContext(), "Dodawanie komentarzy do tego newsa jest zablokowane.",
						Toast.LENGTH_LONG).show();
			}
			return true;
		}
		else if(item.getItemId() == R.id.refresh_bookmark){
			new AsyncActionClass().execute(null);
			return true;
		}
		else{
			 return super.onOptionsItemSelected(item);
		}
	}
	
	
	
	@Override
	protected Intent getIntentToReturnAfterLogout() {
		Intent intent = new Intent(getApplicationContext(), SingleNewsActivity.class);
		intent.putExtra("news_id", news.getId());
		return intent;
	}

	@Override
	protected void doInBackgroundAsyncProcess() throws Exception {
		
			news.setContent(news.getContent().replaceAll("(\r\n|\n)", "<br />"));
			newsContentTextView.setText(Html.fromHtml(news.getContent()));
			newsContentTextView.setSingleLine(false);
			
			newsTitleTextView.setText(news.getTitle());
			newsDateTextView.setText(news.getStringDate());
			
			boolean displayImages = sharedPreferences.getBoolean(MyPreferencesActivity.PREFERENCE_NAME_DISPLAY_NEWS_IMAGES, Boolean.parseBoolean(properties.getProperty(MyPreferencesActivity.PREFERENCE_NAME_DISPLAY_NEWS_IMAGES)));
			boolean displayAvatars = sharedPreferences.getBoolean(MyPreferencesActivity.PREFERENCE_NAME_DISPLAY_AVATARS, Boolean.parseBoolean(properties.getProperty(MyPreferencesActivity.PREFERENCE_NAME_DISPLAY_AVATARS)));
			
			ImageLoader il = new ImageLoader(getApplicationContext());
			
			if(displayImages){
				il.DisplayImage("http://www.juvepoland.com/images/news/"+news.getId()+".jpg", thumbImage);
			}
			else{
				thumbImage.setVisibility(LinearLayout.GONE);
				RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
	        	        ViewGroup.LayoutParams.WRAP_CONTENT);
	        	p.addRule(RelativeLayout.BELOW, R.id.date_single);
	        	((TextView) findViewById(R.id.news_content)).setLayoutParams(p);
	        	
			}
			
			newsIDTextView.setText(String.valueOf(news.getId()));
			sourceTextView.setText(news.getSource());
			
			List<Comment> currentCommentList = commentManager.getCommentsList(news.getId(), commentIndex, commentsCountPerSinglePage);
			
	        adapter = new LazyCommentAdapter(SingleNewsActivity.this, currentCommentList , basicFontTypeFace, basicFontTypeFace, displayAvatars);
			list.setAdapter(adapter);
			
			list.setSelectionFromTop(commentIndex, 0);
			
			if(list.getCount()<commentsCountPerSinglePage || commentIndex >= news.getCommentsCount()){
				btnLoadMore.setClickable(false);
				btnLoadMore.setText("(koniec komentarzy)");
			}
			
			//list.setSelectionFromTop(commentIndex, 0);
			
	
	}


	
	
}
